package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import cc.ufinity.networkdiagnose.chart.ChartManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.HttpTestManager;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.PullTaskParser;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TaskParser;
import cc.ufinity.networkdiagnose.manager.Task.HttpTask;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import android.app.Activity;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

public class HttpTestWidget extends GeneralTestWidget {
    private ScrollView sView;
    private LinearLayout httpTestDetail;
    private HttpTestManager httpTestManager;
    private LinearLayout chartLayout;
    private Button btnRetest;
    // private LinearLayout testResultLayout;
    private Button backBtn;
    private Activity ctx;
    private Task task;
    private String fileName;
    private Handler httpTestHandler;
    private WlanManager wmanager;

    public HttpTestWidget(Activity context) {
        super(context);
        inflate(context, R.layout.http_test_widget, this);
        this.ctx = context;
        backBtn = (Button) findViewById(R.id.http_test_btnBack);
        sView = (ScrollView) this.findViewById(R.id.http_test_ScrView);
        httpTestDetail = (LinearLayout) this.findViewById(R.id.http_test_detail);
        chartLayout = (LinearLayout) this.findViewById(R.id.httpTestChartLayout);
        btnRetest = (Button) findViewById(R.id.btn_http_retest);
        httpTestManager = new HttpTestManager(ctx);

        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                back(ctx);
            }
        });

        btnRetest.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // HttpTestWidget aw = new HttpTestWidget(ctx);
                // ctx.setContentView(aw);
                // aw.startHttpTest();
                if (null != fileName) {
                    new UploadResultTask().execute();
                } else {
                    showMessage(ctx, "文件已上传或未进行HTTP测试.");
                }
            }
        });

        // 定义HTTP 测试句柄，获得每次测试结果
        httpTestHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.HTTP_PAGELOAD_SUCCESS:
                    updateHttpTestResult();
                    setScrollViewDown(sView);
                    break;
                case MessageWhat.HTTP_PAGELOAD_FAILED:
                    dismissProgressDialog();
                    showMessage(ctx,"HTTP测试加载失败.");
                    break;
                case MessageWhat.DONE:
                    drawLineChart();
                    setScrollViewDown(sView);
                    dismissProgressDialog();
                    break;
                case MessageWhat.NETWORK_INVALID:
                    dismissProgressDialog();
                    showMessage(ctx, "无法连接至因特网.");
                    break;
                case MessageWhat.FTP_ACCOUNT_INVALID:
                    dismissProgressDialog();
                    showMessage(ctx, "无法获取FTP账号，请检查FTP配置.");
                    break;
                case MessageWhat.FTP_UPLOAD_TASK_DONE:
                    dismissProgressDialog();
                    showMessage(ctx, "上传成功.");
                    break;
                case MessageWhat.FTP_UPLOAD_FAILED:
                    dismissProgressDialog();
                    showMessage(ctx, "上传失败，请检查FTP配置是否正确.");
                    break;
                case MessageWhat.FTP_LOGIN_FAILED:
                    dismissProgressDialog();
                    showMessage(ctx, "FTP登录失败，请检查FTP配置是否正确.");
                    break;
                }
            }
        };
        httpTestManager.setHandler(httpTestHandler);

        task = new Task();

    }

    public void startHttpTest() {
        final FTPConfig ftp = this.getFTPConfig(ctx);
        if (ftp != null) {
            this.showProgressDialog(ctx, "正在进行HTTP测试...", 5);
            int type = NetworkManager.detectNetworkConnectivity(ctx);
            if (type == -1) {
                sendMsg(MessageWhat.NETWORK_INVALID, httpTestHandler);
            } else {
                initTask(task, ctx, type);
                new Thread() {
                    public void run() {
                        task.startTime = StringUtils.getDateTime();
                        httpTestManager.startHttpTest("http://www.baidu.com", 5);
                    }

                }.start();
            }

        }
    }

    private void drawLineChart() {
        DecimalFormat df = new DecimalFormat("#0.000");
        StringBuffer result = new StringBuffer();
        int times = httpTestManager.getXdata().length;
        long size = httpTestManager.getPageLength();
        float delay = (float) (httpTestManager.totalDelayTime / times);
        float speed = (delay == 0) ? 0 : ((float) size / 1024) / ((float) delay / 1000);
        // Log.e("", String.valueOf(size));
        result.append("测试次数=").append(times);
        result.append(",平均时延=").append(df.format(delay / 1000));
        result.append(" s");
        result.append(",平均下载速率=").append(df.format(speed)).append(" kb/s");
        TextView tv = new TextView(ctx);
        tv.setTextSize(13);
        tv.setTextColor(Color.CYAN);
        tv.setText(result);
        httpTestDetail.addView(tv);
        
        task.testCount = 5;
        HttpTask httpTask = task.newHttpTask("www.baidu.com");
        httpTask.delay = df.format(delay / 1000);
        httpTask.failedTimes = 0;
        ArrayList<HttpTask> httpTasks = new ArrayList<HttpTask>(1);
        httpTasks.add(httpTask);
        task.httpTasks = httpTasks;
        task.endTime = StringUtils.getDateTime();

        ChartManager cm = new ChartManager(ctx, 5, 20);
        String chartTitle = "HTTP页面访问测试";
        String[] lineTitles = new String[] { "页面访问时延" };
        List<double[]> x = new ArrayList<double[]>(1);
        List<double[]> y = new ArrayList<double[]>(1);
        x.add(httpTestManager.getXdata());
        y.add(httpTestManager.getYdata());
        int[] colors = new int[] { Color.GREEN };
        View lineChart = cm.createLineChart(colors, chartTitle, lineTitles, x, y);
        chartLayout.addView(lineChart);

        new UploadResultTask().execute();

    }

    private void updateHttpTestResult() {
        DecimalFormat df = new DecimalFormat("#0.000");
        int currentTime = httpTestManager.getCurrentTime();
        this.setDialogProgress(currentTime);
        long delayTime = httpTestManager.getDelayTime();
        httpTestManager.processing = false;
        StringBuffer sb = new StringBuffer();
        sb.append("第").append(currentTime).append("次 ").append(httpTestManager.getAddress()).append(" 页面访问时延：")
                .append(df.format((float) delayTime / 1000)).append(" s");
        TextView text = new TextView(ctx);
        text.setText(sb);
        text.setTextSize(12);
        httpTestDetail.addView(text);
        
    }
    
    private class UploadResultTask extends AsyncTask<Void, Void, String> {
        protected void onPreExecute() {
            showMessage(ctx, "正在上传结果...");
        }

        @Override
        protected String doInBackground(Void... params) {
            
            if (fileName == null) {
                TaskParser parser = new PullTaskParser();
                fileName = parser.XmlFileCreator(task);
            }
            if (uplod(fileName, ctx, httpTestHandler)) {
                fileName = null;
            }
            return fileName;
        }
/*
        protected void onPostExecute(String result) {
            if (result == null) {
                showMessage(ctx, "上传成功.");
            }
        }*/
    }

}